package nickthissen.iracing.adapters;

import java.util.ArrayList;

import nickthissen.iracing.activities.FavoriteThreadsActivity;
import nickthissen.iracing.datamodels.FavoriteThread;
import nickthissen.iracing.iracingforum2.R;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.TextView;

public class FavoriteThreadListAdapter extends ArrayAdapter<FavoriteThread>
{
	private FavoriteThreadsActivity activity;
	private ArrayList<FavoriteThread> items;
	
	public FavoriteThreadListAdapter(FavoriteThreadsActivity context, int resourceId, ArrayList<FavoriteThread> items)
	{
		super(context, resourceId, items);
		this.activity = context;
		this.items = items;
	}
	
	@Override
	public View getView(int position, View convertView, ViewGroup parent)
	{
		View v = convertView;
		if (v == null)
		{
			LayoutInflater vi = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
			v = vi.inflate(R.layout.favoriterow, null);
		}
		
		FavoriteThread thread = items.get(position);
		if (thread != null)
		{
			v.setClickable(true);
			v.setOnClickListener(new ItemClickListener(thread));
			v.setOnLongClickListener(new ItemLongClickListener(thread));
			v.setOnCreateContextMenuListener(null);
			
			TextView lblTop = (TextView) v.findViewById(R.id.lblTop);
			TextView lblForumTop = (TextView) v.findViewById(R.id.lblForumTop);
			TextView lblForumBottom = (TextView) v.findViewById(R.id.lblForumBottom);
			
			lblTop.setMaxLines(1);
			lblTop.setText(thread.ThreadName);
			
			String[] abbr = thread.ForumName.split(" ", 2);
			if (abbr.length > 0) lblForumTop.setText(abbr[0]);
			if (abbr.length > 1) 
			{
				lblForumBottom.setText(abbr[1]);
				lblForumBottom.setVisibility(View.VISIBLE);
			}
			else
			{
				lblForumBottom.setVisibility(View.GONE);
			}
		}
		return v;
	}
	
	private class ItemClickListener implements View.OnClickListener
	{
		private FavoriteThread thread;
		
		public ItemClickListener(FavoriteThread f)
		{
			this.thread = f;
		}
		
		@Override
		public void onClick(View v)
		{
			activity.onItemClicked(thread);
		}		
	}
	
	private class ItemLongClickListener implements View.OnLongClickListener
	{
		private FavoriteThread thread;
		
		public ItemLongClickListener(FavoriteThread f)
		{
			this.thread = f;
		}
		
		@Override
		public boolean onLongClick(View v)
		{
			return activity.deleteFavorite(thread);
		}		
	}
}
